package cn.edu.ujn.bmis.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.json.annotations.JSON;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.ujn.bmis.model.Inform;
import cn.edu.ujn.bmis.model.OrderBook;
import cn.edu.ujn.bmis.model.SysFunction;
import cn.edu.ujn.bmis.model.UserFunction;
import cn.edu.ujn.bmis.model.UserInfo;
import cn.edu.ujn.bmis.service.BookManager;
import cn.edu.ujn.bmis.service.InformManager;
import cn.edu.ujn.bmis.service.OrderBookManager;
import cn.edu.ujn.bmis.service.SysFunctionManager;
import cn.edu.ujn.bmis.service.UserFunctionManager;
import cn.edu.ujn.bmis.service.UserInfoManager;
import cn.edu.ujn.bmis.tools.Helper;
import cn.edu.ujn.bmis.tools.MD5DigestUtil;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component("UserInfo")
@Scope("prototype")
public class UserInfoAction extends ActionSupport {

	private static final long serialVersionUID = 7450195317409387329L;
	private UserInfoManager userInfoManager;
	private UserInfo userInfo;
	private Helper helper;
	private List<UserInfo> userInfoList = new ArrayList<UserInfo>();
	private String targetType = "navTab"; // navTab或dialog，用来标记是navTab上的分页还是dialog上的分页
	private int pageNum = 1;
	private int currentPage = 1; // 当前是第几页
	private int totalCount = 0; // 总条数
	private int numPerPage = 5; // 每页显示多少条
	private int pageNumShown = 5; // 页标数字多少个
	private int pageCount = 0; // 总页数
	private String orderField;
	private String orderDirection;
	private String userIds;
	private String userId;
	private String userName;
	private String userStatus;
	private String userPassword;
	private String oldPassword;
	private String newPassword;
	private String email;
	private String telephone;
	private String papersNum;
	private List<UserFunction> userFunctionList = new ArrayList<UserFunction>();
	private List<SysFunction> sysFunctionList = new ArrayList<SysFunction>();
	private UserFunctionManager userFunctionManager;
	private UserFunction userFunction;
	private SysFunction sysFunction;
	private String functionNum;
	private String back;
	private InformManager informManager;
	private Inform inform;
	private List<Inform> informList = new ArrayList<Inform>();
	private List<OrderBook> orderBookList=new ArrayList<OrderBook>();
	private OrderBookManager orderBookManager;
	private SysFunctionManager sysFunctionManager;
	private BookManager bookManager;

	/**
	 * 退出系统
	 */
	public String exitSystem(){
		return SUCCESS;
	}
	
	/**
	 * 进入读者登陆界面
	 */
	@SuppressWarnings("unchecked")
	public String reader() {
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		String hql = "";
		hql = "select i from Inform i where i.userInfo.userId='"+users.getUserId()+"' or i.userInfo.userId=null";
		informList = informManager.findInform(hql);
		return SUCCESS;
	}

	/**
	 * 进入管理员登陆界面
	 */
	public String administrator() {
		return SUCCESS;
	}

	/**
	 * 进入添加用户的页面
	 */
	public String beforeAddUserInfo() {
		// 功能权限验证
		if (!helper.checkFunction(functionNum)) {
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		return SUCCESS;
	}

	/**
	 * 读者修改自己的信息
	 */
	public void readerUpdateUserInfo() {

		String hql = "";
		hql = "update UserInfo u set u.userName='" + userName.trim()
				+ "',u.email='" + email.trim() + "'," + "u.telephone='"
				+ telephone.trim() + "',u.papersNum='" + papersNum.trim()
				+ "' " + "where u.userId='" + userId.trim() + "'";
		if (userInfoManager.update(hql)) {
			Helper.out("200", "读者信息更新成功!", "closeCurrent", "", "", "");
		} else {
			Helper.out("300", "读者信息更新失败!", "", "", "", "");
		}
	}

	/**
	 * 用户重置密码
	 */
	@SuppressWarnings("unchecked")
	public void resetPwUserInfo() {
		String hql = "";
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		hql = "from UserInfo u where u.userId='" + users.getUserId() + "'";
		userInfoList = userInfoManager.findUserInfo(hql);
		if (userInfoList.size() > 0) {
			if (!userInfoList.get(0).getUserPassword().equals(
					MD5DigestUtil.EncoderPwdByApacheMd5(oldPassword))) {
				Helper.out("300", "用户旧密码错误,请检查！", "", "", "", "");
				return;
			}
		}
		hql = "update UserInfo u set u.userPassword='"
				+ MD5DigestUtil.EncoderPwdByApacheMd5(newPassword)
				+ "' where u.userId='" + users.getUserId() + "'";
		if (userInfoManager.update(hql)) {
			Helper.out("200", "用户密码重置成功！", "closeCurrent", "", "", "");
		} else {
			Helper.out("300", "用户密码重置失败,请检查！", "", "", "", "");
		}
	}

	/**
	 * 读者查看自己的信息
	 */
	@SuppressWarnings("unchecked")
	public String readerFindUserInfo() {
		String hql = "";
		// 功能权限验证
		if (!helper.checkFunction(functionNum)) {
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		hql = "from UserInfo u where u.userId='" + users.getUserId() + "'";
		userInfoList = userInfoManager.findUserInfo(hql);
		if (userInfoList.size() > 0) {
			userInfo = userInfoList.get(0);
		}
		return SUCCESS;
	}

	/**
	 * 读者重置自己的密码
	 */
	public String readerChangepwd() {
//		// 功能权限验证
//		if (!helper.checkFunction(functionNum)) {
//			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
//		}
		return SUCCESS;
	}

	/**
	 * 用户登录系统
	 */
	@SuppressWarnings("unchecked")
	public String loginUserInfo() {
		String hql = "";
		UserInfo user = new UserInfo();
		if (userId == null) {
			userId = "";
		}
		if (userPassword == null) {
			userPassword = "";
		}
		// 获取当前日期
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String today = formatter.format(date);
		Map session = (Map) ActionContext.getContext().getSession();
		if("admin".equals(userId.trim())&&"admin".equals(userPassword.trim())){
			// 获取功能权限
			ArrayList<String> functionNumList = new ArrayList<String>();
			hql = " from SysFunction s where s.functionNum like 'hxlsysad%'";
			sysFunctionList=sysFunctionManager.findSysFunction(hql);
			
			Iterator iterator = sysFunctionList.iterator();
			while (iterator.hasNext()) {
				sysFunction= (SysFunction) iterator.next();
				functionNumList.add(sysFunction.getFunctionNum());
			}
			user.setUserStatus("系统管理员");
			user.setUserId("admin");
			user.setUserName("admin");
			session.put("user", user);
			session.put("today", today);
			session.put("functionNumList", functionNumList);
			this.back = "系统管理员";
		}else{
			hql = "from UserInfo u where u.userId='" + userId.trim() + "'";
			userInfoList = userInfoManager.findUserInfo(hql);
			if (userInfoList.size() <= 0) {
				this.back = "用户账号不存在,请检查！";
			} else {
				userInfo = userInfoList.get(0);
				if (!userInfo.getUserPassword().equals(
						MD5DigestUtil.EncoderPwdByApacheMd5(userPassword))) {
					this.back = "用户密码错误,请检查！";
				} else {
					//System.out.println("Welcome, " + userInfo.getUserName() + " you have successfully logged in" );
					//用户登录成功的时候先去处理一下过期的预约记录
					String hql_or="from OrderBook o where o.effective=1 and o.endOrderTime<CONVERT('"+today+"', DATE)";
					orderBookList=orderBookManager.findOrderBook(hql_or);
					for(int i=0;i<orderBookList.size();i++){
						String hql_u = "update OrderBook o set o.orderTime=null,o.effective=0,o.endOrderTime=null where o.id='"+ orderBookList.get(i).getId() + "'";
						orderBookManager.updateOrderBook(hql_u);
					}
					if (userInfo.getUserStatus().equals("图书管理员")) {
						// 获取功能权限
						ArrayList<String> functionNumList = new ArrayList<String>();
						hql = " from UserFunction u where u.userInfo.userId='" + userInfo.getUserId() + "'"; 
						userFunctionList = userFunctionManager.findUserFunction(hql);
						Iterator iterator = userFunctionList.iterator();
						while (iterator.hasNext()) {
							userFunction = (UserFunction) iterator.next();
							functionNumList.add(userFunction.getSysFunction().getFunctionNum());
						}
						user.setUserStatus("图书管理员");
						user.setUserId(userInfo.getUserId());
						user.setUserName(userInfo.getUserName());
						user.setEmail(userInfo.getEmail());
						session.put("user", user);
						session.put("today", today);
						session.put("functionNumList", functionNumList);
						this.back = "图书管理员";
					} else if (userInfo.getUserStatus().equals("系统管理员")) {
						// 获取功能权限
						ArrayList<String> functionNumList = new ArrayList<String>();
						hql = " from UserFunction u where u.userInfo.userId='"+ userInfo.getUserId() + "'"; 
						userFunctionList = userFunctionManager.findUserFunction(hql);
						Iterator iterator = userFunctionList.iterator();
						while (iterator.hasNext()) {
							userFunction = (UserFunction) iterator.next();
							functionNumList.add(userFunction.getSysFunction().getFunctionNum());
						}
						user.setUserStatus("系统管理员");
						user.setUserId(userInfo.getUserId());
						user.setUserName(userInfo.getUserName());
						user.setEmail(userInfo.getEmail());
						session.put("user", user);
						session.put("today", today);
						session.put("functionNumList", functionNumList);
						this.back = "系统管理员";
					} else if (userInfo.getUserStatus().equals("读者")) {
						// 获取功能权限
						ArrayList<String> functionNumList = new ArrayList<String>();
						hql = " from UserFunction u where u.userInfo.userId='" + userInfo.getUserId() + "'"; 
						userFunctionList = userFunctionManager.findUserFunction(hql);
						Iterator iterator = userFunctionList.iterator();
						while (iterator.hasNext()) {
							userFunction = (UserFunction) iterator.next();
							functionNumList.add(userFunction.getSysFunction().getFunctionNum());
						}
						user.setUserStatus("读者");
						user.setUserId(userInfo.getUserId());
						user.setUserName(userInfo.getUserName());
						user.setEmail(userInfo.getEmail());
						session.put("user", user);
						session.put("today", today);
						session.put("functionNumList", functionNumList);
						this.back = "读者";
					}
				}
			}
		}
		return SUCCESS;
	}

	/**
	 * 添加用户
	 */
	public void addUserInfo() {
		String hql="";
		if(userInfo!=null){
			hql=" from UserInfo u where u.userId='"+userInfo.getUserId()+"'";
			userInfoList=userInfoManager.findUserInfo(hql);
			if(userInfoList.size()>0){
				Helper.out("300", "用户编号已存在，请检查！", "", "", "", "");
				return;
			}
		}
		userInfo.setUserPassword(MD5DigestUtil.EncoderPwdByApacheMd5(userInfo
				.getUserPassword()));
		if (userInfoManager.addUser(userInfo)) {
			Helper.out("200", "用户添加成功", "closeCurrent", "", "",
					"manageUserInfo");
		} else {
			Helper.out("300", "用户添加失败", "", "", "", "");
		}
	}
	
	/**
	 * 注册用户
	 */
	public String registerUserInfo(){
//		String hql = "";
//		hql = " from UserInfo u where u.userId='" + userId + "'";
//		userInfoList = userInfoManager.findUserInfo(hql);
//		if (userInfoList.size() > 0) {
//			Helper.out("300", "用户编号已存在，请检查！", "", "", "", "");
//		}
//		UserInfo user=new UserInfo();
//		user.setUserId(userId);
//		user.setUserName(userName);
//		user.setUserPassword(MD5DigestUtil.EncoderPwdByApacheMd5(userPassword));
//		user.setEmail(email);
//		user.setTelephone(telephone);
//		user.setPapersNum(papersNum);
//		user.setUserStatus(userStatus);
//		boolean b=userInfoManager.addUser(user);
//		if (b) {
//			this.back="注册成功";
//		} else {
//			this.back="注册失败";
//		}
		this.back="注册成功";
		return SUCCESS;
	}

	/**
	 * 删除用户
	 */
	public void deleteUserInfo() {
		// 功能权限验证
		if (!helper.checkFunction(functionNum)) {
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
			return;
		}
		String[] strArray = null;
		strArray = userIds.split(",");
		String hql = null;
		hql = "delete from UserInfo u where u.userId in ('";
		for (int i = 0; i < strArray.length - 1; i++) {
			hql = hql + strArray[i] + "'" + ",'";
		}
		hql = hql + strArray[strArray.length - 1] + "') ";
		if (userInfoManager.update(hql)) {
			Helper.out("200", "用户信息删除成功", "", "", "", "manageUserInfo");
		} else {
			Helper.out("300", "用户信息删除失败", "", "", "", "");
		}
	}

	/**
	 * 修改前的查找
	 */
	public String beforeupdateUserInfo() {
		// 功能权限验证
		if (!helper.checkFunction(functionNum)) {
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql = "from UserInfo u where u.userId='" + userId + "'";
		userInfoList = userInfoManager.findUserInfo(hql);
		if (userInfoList.size() > 0) {
			userInfo = userInfoList.get(0);
		}
		return SUCCESS;
	}

	/**
	 * 修改用户信息
	 */
	public void updateUserInfo() {
		if (userInfoManager.update(userInfo)) {
			Helper.out("200", "用户信息修改成功", "closeCurrent", "", "",
					"manageUserInfo");
		} else {
			Helper.out("300", "用户信息修改失败", "", "", "", "");
		}
	}

	/**
	 * 查看用户
	 */
	@SuppressWarnings("unchecked")
	public String findUserInfo() {
		String hql = "";
		String hql_size = "";
		// 功能权限验证
		if (!helper.checkFunction(functionNum)) {
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		this.currentPage = this.pageNum;
		hql = "from UserInfo u where u.userId = u.userId ";
		hql_size = "select count(*) from UserInfo u where u.userId = u.userId ";
		if(userId!=null&&!"".equals(userId)){
			hql+=" and u.userId='" + userId.trim() + "' ";
			hql_size+=" and u.userId='" + userId.trim() + "' ";
		}
		if(userName!=null&&!"".equals(userName)){
			hql+=" and u.userName like '%" + userName.trim()+ "%'";
			hql_size+=" and u.userName like '%" + userName.trim()+ "%'";
		}
		if(userStatus!=null&&!"0".equals(userStatus)){
			hql+=" and u.userStatus='" + userStatus.trim() + "'";
			hql_size+=" and u.userStatus='" + userStatus.trim() + "'";
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		userInfoList = helper.fenYe(hql, this.currentPage, this.numPerPage);

		return SUCCESS;
	}

	@Resource(name = "userInfoManager")
	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	@JSON(serialize = false)
	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	@Resource(name = "helper")
	public void setHelper(Helper helper) {
		this.helper = helper;
	}

	@JSON(serialize = false)
	public String getTargetType() {
		return targetType;
	}

	public void setTargetType(String targetType) {
		this.targetType = targetType;
	}

	@JSON(serialize = false)
	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	@JSON(serialize = false)
	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	@JSON(serialize = false)
	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	@JSON(serialize = false)
	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	@JSON(serialize = false)
	public int getPageNumShown() {
		return pageNumShown;
	}

	public void setPageNumShown(int pageNumShown) {
		this.pageNumShown = pageNumShown;
	}

	@JSON(serialize = false)
	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	@JSON(serialize = false)
	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	@JSON(serialize = false)
	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	@JSON(serialize = false)
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	@JSON(serialize = false)
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@JSON(serialize = false)
	public String getUserStatus() {
		return userStatus;
	}

	public void setUserStatus(String userStatus) {
		this.userStatus = userStatus;
	}

	@JSON(serialize = false)
	public List<UserInfo> getUserInfoList() {
		return userInfoList;
	}

	public void setUserInfoList(List<UserInfo> userInfoList) {
		this.userInfoList = userInfoList;
	}

	@JSON(serialize = false)
	public String getUserIds() {
		return userIds;
	}

	public void setUserIds(String userIds) {
		this.userIds = userIds;
	}

	@JSON(serialize = false)
	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	@JSON(serialize = false)
	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	@JSON(serialize = false)
	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	@JSON(serialize = false)
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@JSON(serialize = false)
	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	@JSON(serialize = false)
	public String getPapersNum() {
		return papersNum;
	}

	public void setPapersNum(String papersNum) {
		this.papersNum = papersNum;
	}

	@JSON(serialize = false)
	public List<UserFunction> getUserFunctionList() {
		return userFunctionList;
	}
	@JSON(serialize = false)
	public List<SysFunction> getSysFunctionList() {
		return sysFunctionList;
	}

	@Resource(name = "userFunctionManager")
	public void setUserFunctionManager(UserFunctionManager userFunctionManager) {
		this.userFunctionManager = userFunctionManager;
	}

	@JSON(serialize = false)
	public UserFunction getUserFunction() {
		return userFunction;
	}

	public void setUserFunction(UserFunction userFunction) {
		this.userFunction = userFunction;
	}

	@JSON(serialize = false)
	public String getFunctionNum() {
		return functionNum;
	}
	
	@JSON(serialize = false)
	public SysFunction getSysFunction() {
		return sysFunction;
	}

	public void setSysFunction(SysFunction sysFunction) {
		this.sysFunction = sysFunction;
	}

	public void setFunctionNum(String functionNum) {
		this.functionNum = functionNum;
	}

	public String getBack() {
		return back;
	}

	@JSON(serialize = false)
	public Inform getInform() {
		return inform;
	}

	public void setInform(Inform inform) {
		this.inform = inform;
	}

	@JSON(serialize = false)
	public List<Inform> getInformList() {
		return informList;
	}

	@Resource(name = "informManager")
	public void setInformManager(InformManager informManager) {
		this.informManager = informManager;
	}

	@Resource(name="orderBookManager")
	public void setOrderBookManager(OrderBookManager orderBookManager) {
		this.orderBookManager = orderBookManager;
	}
	
	@Resource(name="sysFunctionManager")
	public void setSysFunctionManager(SysFunctionManager sysFunctionManager) {
		this.sysFunctionManager = sysFunctionManager;
	}
	
	@Resource(name="bookManager")
	public void setBookManager(BookManager bookManager) {
		this.bookManager = bookManager;
	}
	
	
	
}
